// 这个文件包含所有utils模块中需要的unsafe操作
// 它应该只被utils模块中的安全包装函数调用

use std::ffi::{CStr};
use std::ptr;

/// 不安全的字符串操作帮助函数
pub unsafe fn unsafe_cstr_to_string(c_str_ptr: *const i8) -> Result<String, ()> {
    let c_str = CStr::from_ptr(c_str_ptr);
    c_str.to_str()
        .map(|s| s.to_string())
        .map_err(|_| ())
}

/// 不安全的C字符串复制操作
pub unsafe fn unsafe_copy_c_string(
    source: *const i8,
    destination: *mut i8,
    max_length: u32
) -> u32 {
    let source_len = CStr::from_ptr(source).to_bytes().len();
    let copy_len = std::cmp::min(source_len, (max_length - 1) as usize);
    
    ptr::copy_nonoverlapping(source as *const u8, destination as *mut u8, copy_len);
    *destination.offset(copy_len as isize) = 0;
    
    copy_len as u32
}

/// 不安全的C字符串长度计算
pub unsafe fn unsafe_c_string_length(c_str_ptr: *const i8) -> u32 {
    CStr::from_ptr(c_str_ptr).to_bytes().len() as u32
}

/// 不安全的C字符串比较
pub unsafe fn unsafe_compare_c_strings(str1: *const i8, str2: *const i8) -> bool {
    let c_str1 = CStr::from_ptr(str1);
    let c_str2 = CStr::from_ptr(str2);
    c_str1 == c_str2
}

/// 不安全的u8读取
pub unsafe fn unsafe_read_u8(buffer: *const u8, offset: u32) -> u8 {
    *buffer.offset(offset as isize)
}

/// 不安全的u8写入
pub unsafe fn unsafe_write_u8(buffer: *mut u8, offset: u32, value: u8) {
    *buffer.offset(offset as isize) = value;
}

/// 不安全的u16小端序读取
pub unsafe fn unsafe_read_u16_le(buffer: *const u8, offset: u32) -> u16 {
    let ptr = buffer.offset(offset as isize) as *const u16;
    u16::from_le(*ptr)
}

/// 不安全的u16小端序写入
pub unsafe fn unsafe_write_u16_le(buffer: *mut u8, offset: u32, value: u16) {
    let ptr = buffer.offset(offset as isize) as *mut u16;
    *ptr = value.to_le();
}

/// 不安全的u32小端序读取
pub unsafe fn unsafe_read_u32_le(buffer: *const u8, offset: u32) -> u32 {
    let ptr = buffer.offset(offset as isize) as *const u32;
    u32::from_le(*ptr)
}

/// 不安全的u32小端序写入
pub unsafe fn unsafe_write_u32_le(buffer: *mut u8, offset: u32, value: u32) {
    let ptr = buffer.offset(offset as isize) as *mut u32;
    *ptr = value.to_le();
}

/// 不安全的u64小端序读取
pub unsafe fn unsafe_read_u64_le(buffer: *const u8, offset: u32) -> u64 {
    let ptr = buffer.offset(offset as isize) as *const u64;
    u64::from_le(*ptr)
}

/// 不安全的u64小端序写入
pub unsafe fn unsafe_write_u64_le(buffer: *mut u8, offset: u32, value: u64) {
    let ptr = buffer.offset(offset as isize) as *mut u64;
    *ptr = value.to_le();
}

/// 不安全的指针值设置（用于结果代码等简单类型）
pub unsafe fn unsafe_set_ptr_value<T>(ptr: *mut T, value: T) {
    *ptr = value;
}

/// 不安全的内存块复制
pub unsafe fn unsafe_copy_memory_block(
    source: *const u8,
    destination: *mut u8,
    length: usize
) {
    destination.copy_from_nonoverlapping(source, length);
}

/// 不安全的获取CStr引用（用于临时使用，不转换为String）
pub unsafe fn unsafe_get_cstr_ref(c_str_ptr: *const i8) -> &'static CStr {
    CStr::from_ptr(c_str_ptr)
}